package com.hlcl.huaji.utils;

import android.content.Context;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;


import java.util.ArrayList;
import java.util.List;

/**
 * Created by Wang on 11/14/16.
 * 自定义标签，支持自动换行
 * <p>
 * 添加标签水平居中功能2017-10-16 horry
 */
public class MyTagView extends ViewGroup {

    //水平间距，默认10 单位dp
    private int horizontalSpace = 0;
    private boolean singleLine = false;

    private int maxLine = 0;

    public MyTagView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public MyTagView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MyTagView(Context context) {
        this(context, null);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        layoutHorizontal();
    }

    public void resetTags() {
        for (int i = 0; i < getChildCount(); i++) {
            View view = getChildAt(i);
            view.setSelected(false);
        }
    }

    List<TagWrapper> lineViews = new ArrayList<>();

    private int gravity = Gravity.LEFT;

    public void setGravity(int gravity) {
        this.gravity = gravity;
    }

    /**
     * 计算横向宽度是否能在一行显示全，如果显示不全则折行
     */
    private void layoutHorizontal() {
        maxLine = 0;
        lineViews.clear();
        final int count = getChildCount();
        final int lineWidth = getMeasuredWidth() - getPaddingLeft() - getPaddingRight();
        int paddingTop = getPaddingTop();
        int childTop;
        int childLeft = getPaddingLeft();

        int availableLineWidth = lineWidth;

        int maxLineHeight = 0;

        for (int i = 0; i < count; i++) {
            final View child = getChildAt(i);
            if (child != null && child.getVisibility() != GONE) {

                final int childWidth = child.getMeasuredWidth();
                final int childHeight = child.getMeasuredHeight();

                if (availableLineWidth < childWidth) {//换行
                    maxLine++;
                    if (singleLine) {
                        break;
                    }
                    availableLineWidth = lineWidth;
                    paddingTop = paddingTop + maxLineHeight;
                    childLeft = getPaddingLeft();
                    maxLineHeight = 0;
                }

                childTop = paddingTop;

                if (gravity == Gravity.CENTER_HORIZONTAL) {
                    TagWrapper tagWrapper = new TagWrapper();
                    tagWrapper.setTopPosition(childTop);
                    tagWrapper.setView(child);
                    tagWrapper.setLineNum(maxLine);
                    lineViews.add(tagWrapper);

                    availableLineWidth = availableLineWidth - childWidth - DensityUtil.dp2px(getContext(), horizontalSpace);

                } else {
                    setChildFrame(child, childLeft, childTop, childWidth, childHeight);
                    childLeft += childWidth + DensityUtil.dp2px(getContext(), horizontalSpace);
                    availableLineWidth = availableLineWidth - childWidth - DensityUtil.dp2px(getContext(), horizontalSpace);
                }
                maxLineHeight = Math.max(maxLineHeight, childHeight);
            }
        }

        layoutChild(lineWidth);
    }

    private void layoutChild(int lineWidth) {

        for (int i = 0; i <= maxLine; i++) {

            List<TagWrapper> wrapperList = new ArrayList<>();

            for (int j = 0; j < lineViews.size(); j++) {

                TagWrapper tagWrapper = lineViews.get(j);

                if (tagWrapper.getLineNum() == i) {
                    wrapperList.add(tagWrapper);
                }
            }

            int childLeft;
            int userWidth = 0;

            for (TagWrapper wrapper :
                    wrapperList) {
                userWidth += wrapper.getView().getMeasuredWidth() + DensityUtil.dp2px(getContext(), horizontalSpace);
            }

            userWidth -= DensityUtil.dp2px(getContext(), horizontalSpace);

            int beforeUseSpace = 0;//签名标签的净长度

            int listSize = wrapperList.size();

            int startX = getPaddingLeft() + (lineWidth - userWidth) / 2;

            for (int j = 0; j < listSize; j++) {

                if (j == 0) {
                    childLeft = startX;
                } else {
                    childLeft = startX + beforeUseSpace;
                }

                View child = wrapperList.get(j).getView();
                int childWidth = child.getMeasuredWidth();

                setChildFrame(child, childLeft, wrapperList.get(j).getTopPosition(), childWidth, child.getMeasuredHeight());

                beforeUseSpace += childWidth + DensityUtil.dp2px(getContext(), horizontalSpace);
            }
        }
    }

    private void setChildFrame(View child, int left, int top, int width, int height) {
        child.layout(left, top, left + width, top + height);
    }

    public void setHorizontalSpace(int horizontalSpace) {
        this.horizontalSpace = horizontalSpace;
    }

    public void setSingleLine(boolean singleLine) {
        this.singleLine = singleLine;
        requestLayout();
    }

    public boolean isSingleLine() {
        return singleLine;
    }

    public int getMaxLine() {
        return maxLine;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int count = getChildCount();
        for (int i = 0; i < count; i++) {
            measureChild(getChildAt(i), widthMeasureSpec, heightMeasureSpec);
        }
        if (heightMode == MeasureSpec.AT_MOST || heightMode == MeasureSpec.UNSPECIFIED) {
            final int width = MeasureSpec.getSize(widthMeasureSpec);
            super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(getDesiredHeight(width), MeasureSpec.EXACTLY));
        } else {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }


    private int lineNumbersAll = 0;//总行数
    private List<Integer> numberCount = new ArrayList<Integer>();//某一行的累计个数
    private List<Integer> numberHeight = new ArrayList<>();//某一行的累计高度
    private int totalHeight;

    private int getDesiredHeight(int width) {
        lineNumbersAll = 0;
        numberCount.clear();
        numberHeight.clear();
        final int lineWidth = width - getPaddingLeft() - getPaddingRight();
        int availableLineWidth = lineWidth;
        totalHeight = getPaddingTop() + getPaddingBottom();
        int lineHeight = 0;
        for (int i = 0; i < getChildCount(); i++) {
            View child = getChildAt(i);
            final int childWidth = child.getMeasuredWidth();
            final int childHeight = child.getMeasuredHeight();
            if (availableLineWidth < childWidth) {
                if (singleLine) {
                    break;
                }
                lineNumbersAll++;
                numberCount.add(i + 1);
                availableLineWidth = lineWidth;
                totalHeight = totalHeight + lineHeight;
                numberHeight.add(totalHeight);
                lineHeight = 0;
            }
            availableLineWidth = availableLineWidth - childWidth - DensityUtil.dp2px(getContext(), horizontalSpace);
            lineHeight = Math.max(childHeight, lineHeight);

        }
        totalHeight = totalHeight + lineHeight;
        return totalHeight;
    }

    public int getLineNumbersAll() {
        return lineNumbersAll;
    }


    public List<Integer> getNumberCounts() {
        return numberCount;
    }

    public List<Integer> getNumberHeight() {
        return numberHeight;
    }


    public int getTotalHeight() {
        return totalHeight;
    }


   private class TagWrapper {
        private int lineNum;
        private int topPosition;
        private View view;

        public int getLineNum() {
            return lineNum;
        }

        public void setLineNum(int lineNum) {
            this.lineNum = lineNum;
        }

        public int getTopPosition() {
            return topPosition;
        }

        public void setTopPosition(int topPosition) {
            this.topPosition = topPosition;
        }

        public View getView() {
            return view;
        }

        public void setView(View view) {
            this.view = view;
        }
    }
//    private int leftMargin = 0;
//    private int topMargin = 0;
//
//    public void setMargin(int left, int top) {
//        leftMargin = left;
//        topMargin = top;
//    }

}